library(fixest)
library(kableExtra)
library(magrittr)
library(tidyverse)
library(texreg)
library(ggiplot)

################################################################################
# Data Preparation
################################################################################

# read data
df <- read_csv("../data/regdata.csv") %>% filter(Land == 7)

# define colors of the parties
party_colors <- c(
    CDU_share = "#32302e",
    SPD_share = "#e3000f",
    GRUENE_share = "#46962b",
    FDP_share = "#ffed00",
    DIE_LINKE_share = "#b61c3e",
    AfD_share = "#009ee0",
    Wahlbeteiligung = "orange"
)

# Regression in function form
myreg <- function(y,
                  x,
                  weights = ~Gueltige,
                  subset) {
    x <- paste(x, collapse = "+")
    ff <- paste(y, "~", x, "|Verbandsgemeindeschluessel + year^Kreisschluessel")
    feols(
        as.formula(ff),
        cluster = ~Verbandsgemeindeschluessel,
        data = df,
        weights = weights,
        subset = subset
    )
}

myregtable <- function(y,
                       x_vec = xx_did,
                       weights = ~Gueltige,
                       subset,
                       suffix = "") {
    if ((!is.null(weights)) && (weights == ~Gueltige) && (y == "Wahlbeteiligung")) {
        weights <- ~Wahlberechtigte
    }
    did <- map(
        x_vec,
        myreg,
        y = y,
        weights = weights,
        subset = subset
    )
    esttex(
        did,
        file = paste0("../results/tables/regresults_", y, suffix, ".tex"),
        replace = TRUE,
        digits = 3,
        drop = "Total number of"
    )
}

myeventstudy <- function(y,
                         x,
                         weights = ~Gueltige,
                         subset) {
    if ((!is.null(weights)) && (weights == ~Gueltige) && (y == "Wahlbeteiligung")) {
        weights <- ~Wahlberechtigte
    }
    x <- paste(x, collapse = "+")
    ff <- paste(
        y,
        "~",
        "i(year,",
        x,
        ",ref = 2017)",
        "|Verbandsgemeindeschluessel + year^Kreisschluessel"
    )
    feols(
        as.formula(ff),
        cluster = ~Verbandsgemeindeschluessel,
        data = df,
        weights = weights,
        subset = subset
    )
}

myeventstudyplot <- function(x,
                             y_vec = party_shares,
                             weights = ~Gueltige,
                             subset,
                             suffix = "",
                             col = NULL,
                             legend = NULL) {
    if (length(y_vec) > 1) {
        es <- map(
            y_vec,
            myeventstudy,
            x = x,
            weights = weights,
            subset = subset
        )
    } else {
        es <- myeventstudy(
            y_vec,
            x = x,
            weights = weights,
            subset = subset
        )
    }

    pp <- ggiplot(
        es,
        ref.line = 2017,
        pt.join = TRUE,
        col = party_colors[[y_vec]],
        main = "",
        lwd = 2,
        xlab = "",
        ylab = "",
        pt.cex = 2,
        geom_style = 'errorbar'
    ) +
    theme_bw() +
    scale_x_continuous(breaks = c(2009, 2013, 2017, 2021)) +
    theme(
        axis.text = element_text(size = rel(1.5))
    )
    ggsave(paste0("../results/figures/regresults_", x, suffix, ".png"), height = 3, width = 5)
}

setFixest_dict(
    c(
        CDU_share = "Percentage of votes for CDU",
        SPD_share = "Percentage of votes for SPD",
        GRUENE_share = "Percentage of votes for Green Party",
        FDP_share = "Percentage of votes for FDP",
        DIE_LINKE_share = "Percentage of votes for Left Party",
        AfD_share = "Percentage of votes for AfD",
        Wahlbeteiligung = "Turnout",
        ideology = "Environmental ideology",
        to_flooded_p = "Distance to any flooding",
        flooded_area_p = "Share of area flooded",
        ratio_damaged_p = "Share of buildings damaged",
        ratio_total_p = "Share of buildings affected",
        to_flooded_0_10km_p = "0 to 10km from any flooding",
        to_flooded_10_20km_p = "10 to 20km from any flooding",
        log_to_flooded_p = "Log distance to any flooding",
        Verbandsgemeindeschluessel = "Municipality",
        Kreisschluessel = "County",
        year = "Year",
        ratio_total_10_norm_p = "Norm. Share of buildings affected 0-10km",
        ratio_total_20_norm_p = "Norm. Share of buildings affected 10-20km",
        ratio_damaged_10_norm_p = "Norm. Share of buildings damaged 0-10km",
        ratio_damaged_20_norm_p = "Norm. Share of buildings damaged 10-20km"
    )
)
setFixest_etable(
    fitstat = c("my", "n", "ar2", "wr2"),
    style.tex = style.tex("aer"),
    digits.stats = 4
)


################################################################################
# Table 1
################################################################################
xx <- list(
    "log_to_flooded_p",
    "to_flooded_0_10km_p",
    c(
        "to_flooded_0_10km_p",
        "to_flooded_10_20km_p"
    ),
    "flooded_area_p",
    "ratio_total_p",
    "ratio_damaged_p"
)
myregtable("GRUENE_share", x_vec = xx, suffix = "_table_1")

################################################################################
# Figure 3
################################################################################
xx_es <- substr(xx, 1, nchar(xx) - 2)
walk(xx_es[c(1, 2, 4, 5, 6)], myeventstudyplot, y_vec = "GRUENE_share")

################################################################################
# Table 2
################################################################################
xx <- list(
    "ratio_total_10_norm_p",
    c(
        "ratio_total_10_norm_p",
        "ratio_total_20_norm_p"
    ),
    "ratio_damaged_10_norm_p",
    c(
        "ratio_damaged_10_norm_p",
        "ratio_damaged_20_norm_p"
    )
)
myregtable(
    "GRUENE_share",
    x_vec = xx,
    subset = (df$ratio_total == 0),
    suffix = "_table_2"
)

################################################################################
# Table 3
################################################################################
xx <- list(
    "flooded_area_p",
    "ratio_total_p",
    "ratio_damaged_p"
)
other_parties <- c(
    "CDU_share",
    "SPD_share",
    "FDP_share",
    "DIE_LINKE_share",
    "AfD_share",
    "ideology"
)
walk(other_parties, myregtable, x_vec = xx, suffix = "_table_3")

################################################################################
# Table 4
################################################################################
xx <- list(
    "flooded_area_p",
    "ratio_total_p"
)
# only NRW
df <- read_csv("../data/regdata.csv") %>% filter(Land == 5)
myregtable("GRUENE_share", x_vec = xx, suffix = "_nrw_table_4")
# both
df <- read_csv("../data/regdata.csv") %>% filter(Land == 5 | Land == 7)
myregtable("GRUENE_share", x_vec = xx, suffix = "_both_table_4")
